import React, { Component } from "react";
import axios from "axios";

import store from "../../../redux";
import Api from "../../../config/api";

import Navbar from "../../../Component/navbar";

import Button from "antd/lib/button";
import Table from "antd/lib/table";
import Form from "antd/lib/form";
import Spin from "antd/lib/spin";
import Icon from "antd/lib/icon";
import DatePicker from "antd/lib/date-picker";

import moment from "moment";
import "moment/locale/zh-cn";
moment.locale("zh-cn");

const FormItem = Form.Item;
const { MonthPicker } = DatePicker;
const antIcon = (
  <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />
);

let oper = null;

function formatMonth(value) {
  if (parseInt(value, 10) < 10) {
    return "0" + value;
  } else {
    return value;
  }
}

function getMonth() {
  let now = new Date();
  let month, year;
  month = now.getMonth() + 1;
  year = now.getFullYear();
  return year + "-" + formatMonth(month);
}

class OperBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: "",
      endDate: "",
      startMonent: null,
      endMoment: null
    };
  }
  componentDidMount() {
    this.search();
    this.setState({
      startMoment: moment(getMonth(), "YYYY-MM")
    });
  }
  getTime(type, moment, val) {
    if (type === "start") {
      this.setState({
        startDate: val,
        startMoment: moment
      });
    } else {
      this.setState({
        endDate: val,
        endMoment: moment
      });
    }
  }
  disabledstartTime(current) {
    if (this.state.endMoment) {
      return current > this.state.endMoment;
    } else {
      return false;
    }
  }
  disabledendTime(current) {
    if (this.state.startMoment) {
      return current < this.state.startMoment;
    } else {
      return false;
    }
  }
  search() {
    let obj = {
      startTime: this.state.startDate,
      endTime: this.state.endDate
    };
    this.props.search(obj);
  }
  render() {
    const dateFormat = "YYYY-MM";
    return (
      <Navbar ref={(item) => {oper=item}}>
        <Form layout="inline">
          <FormItem label="开始月份">
            <MonthPicker
              format={dateFormat}
              // defaultValue={moment(this.state.startDate, "YYYY-MM")}
              disabledDate={this.disabledstartTime.bind(this)}
              onChange={this.getTime.bind(this, "start")}
            />
          </FormItem>
          <FormItem label="结束月份">
            <MonthPicker
              format={dateFormat}
              disabledDate={this.disabledendTime.bind(this)}
              onChange={this.getTime.bind(this, "end")}
            />
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              icon="search"
              onClick={this.search.bind(this)}
            >
              查询
            </Button>
          </FormItem>
        </Form>
      </Navbar>
    );
  }
}

class Table1 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataNum: 0,
      tableHeight: 300,
      tableData: this.props.tableData,
      currentPage: 1
    };
  }
  componentDidMount() {
    setTimeout(() => {
      let operbarHeight = oper.box.offsetHeight + 10 + 10;
      this.setState({
        tableHeight:
          store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
      });
      this.unscribe = store.subscribe(this.fullTable.bind(this));
    }, 100);
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      tableData: nextProps.tableData,
      dataNum: nextProps.dataNum,
      currntPage: nextProps.currentPage
    });
  }
  componentWillUnmount() {
    this.unscribe();
  }
  fullTable() {
    let operbarHeight = oper.box.offsetHeight + 10 + 10;
    this.setState({
      tableHeight:
        store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
    });
  }
  downLoadBill(data){
    document.location.href = Api['getMsgByMonthBySystemBill']+`?month=${data.month}`;
  }
  render() {
    const columns = [
      { title: "时间", dataIndex: "month", key: "1", width: 200 },
      { title: "发送总数", dataIndex: "msgCount", key: "2", width: 200 },
      { title: "行业总数", dataIndex: "industryMsgCount", key: "3", width: 200 },
      { title: "营销总数", dataIndex: "marketingMsgCount", key: "4", width: 200 },
      {
        title: "成功数",
        key: "5",
        width: 200,
        render: record => {
          return <span style={{ color: "green" }}>{record.successCount}</span>;
        }
      },
      {
        title: "失败数",
        key: "6",
        width: 200,
        render: record => {
          return <span style={{ color: "red" }}>{record.failureCount}</span>;
        }
      },
      { title: "未知数", dataIndex: "unknownCount", key: "7", width: 200 },
      {
        title: "成功率",
        key: "8",
        width: 200,
        render: record => {
          return <span style={{ color: "#104E8B" }}>{record.successRate}</span>;
        }
      },
      {
        title: '操作',
        key: '9',
        width: 100,
        fixed: 'right',
        render: (record) => {
            return (
                <div>
                    <a onClick={this.downLoadBill.bind(this, record)}>账单明细</a>
                </div>
            )
        }
      }
    ];
    return (
      <div className="common-table">
        <Table
          title={data => {
            return "系统月发送统计";
          }}
          columns={columns}
          dataSource={this.state.tableData}
          pagination={{
            onChange: this.props.changePage,
            onShowSizeChange: this.props.changePageSize,
            defaultPageSize: 20,
            pageSizeOptions: ["20", "50", "100"],
            showSizeChanger: true,
            showQuickJumper: true,
            current: this.state.currntPage,
            total: this.state.dataNum,
            showTotal: total => `共 ${total} 条数据`
          }}
          scroll={{ x: 1500, y: this.state.tableHeight }}
        />
      </div>
    );
  }
}

class Box extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      tableData: [],
      searchParams: {},
      totalNum: 0,
      paginationData: {
        current: 1,
        pageNum: 1,
        pageSize: 20
      },
      currentPage: 1
    };
  }
  setParams(obj) {
    this.setState(
      {
        searchParams: obj
      },
      () => {
        this.search("btn");
      }
    );
  }
  search(type) {
    let data = JSON.parse(JSON.stringify(this.state.searchParams));
    if (type === "btn") {
      data.pageNum = 1;
      this.setState({
        currentPage: 1
      });
    } else {
      data.pageNum = this.state.paginationData.pageNum;
    }
    data.pageSize = this.state.paginationData.pageSize;
    this.setState({
      loading: true
    });
    axios
      .post(Api["querySystemMonthStatistic"], data)
      .then(res => {
        if (res) {
          let data = JSON.parse(JSON.stringify(res.data));
          data.list.forEach((item, index) => {
            item.key = index;
          });
          this.setState({
            loading: false,
            tableData: data.list,
            totalNum: data.total
          });
        }
      })
      .catch(error => {
        console.log(error);
      });
  }
  changePageSize(current, size) {
    let pagination = JSON.parse(JSON.stringify(this.state.paginationData));
    pagination.pageNum = current;
    pagination.pageSize = size;
    this.setState(
      {
        paginationData: pagination,
        currentPage: current
      },
      () => {
        this.search("pag");
      }
    );
  }
  changePage(pageNum, pageSize) {
    let pagination = JSON.parse(JSON.stringify(this.state.paginationData));
    pagination.pageNum = pageNum;
    pagination.pageSize = pageSize;
    this.setState(
      {
        paginationData: pagination,
        currentPage: pageNum
      },
      () => {
        this.search("pag");
      }
    );
  }
  render() {
    return (
      <div>
        <OperBar search={this.setParams.bind(this)} />
        <Spin spinning={this.state.loading} indicator={antIcon}>
          <Table1
            currentPage={this.state.currentPage}
            tableData={this.state.tableData}
            dataNum={this.state.totalNum}
            changePageSize={this.changePageSize.bind(this)}
            changePage={this.changePage.bind(this)}
          />
        </Spin>
      </div>
    );
  }
}

export default Box;
